package com.ruoyi.order.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.merchant.api.RemoteMerchantService;
import com.ruoyi.order.domain.Coupon;
import com.ruoyi.order.domain.UserCoupon;
import com.ruoyi.order.mapper.CouponMapper;
import com.ruoyi.order.mapper.UserCouponMapper;
import com.ruoyi.order.service.OrderProducer;
import com.ruoyi.order.utils.OrdersData;
import com.ruoyi.order.utils.RedisIdWorker;
import com.ruoyi.order.utils.VerifyCodeGen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.order.mapper.OrdersMapper;
import com.ruoyi.order.domain.Orders;
import com.ruoyi.order.service.IOrdersService;

/**
 * 订单信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-09
 */
@Service
public class OrdersServiceImpl implements IOrdersService 
{
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private VerifyCodeGen verifyCodeGen;

    @Autowired
    private OrderProducer orderProducer;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private UserCouponMapper userCouponMapper;

    @Autowired
    private RemoteMerchantService romoteMerchantService;

    /**
     * 查询订单信息
     * 
     * @param oId 订单信息主键
     * @return 订单信息
     */
    @Override
    public Orders selectOrdersByOId(Long oId)
    {
        return ordersMapper.selectOrdersByOId(oId);
    }

    /**
     * 查询订单信息列表
     * 
     * @param orders 订单信息
     * @return 订单信息
     */
    @Override
    public List<OrdersData> selectOrdersList(Orders orders) {
        // 对里面的数据进行修改
        List<OrdersData> ordersList = ordersMapper.selectOrdersList(orders);
        System.out.println("列表信息：" + ordersList);
        ordersList.forEach(order -> {
            // 根据服务id多个查询服务名
            System.out.println(order);
            romoteMerchantService.selectServiceManagementBySmId(5L);
        });
        System.out.println("列表信息：" + ordersList);
        return ordersList;
    }
    /**
     * 新增订单信息
     * 
     * @param orders 订单信息
     * @return 结果
     */
    @Override
    public int insertOrders(Orders orders) {
        return ordersMapper.insertOrders(orders);
    }

    /**
     * 修改订单信息
     * 
     * @param orders 订单信息
     * @return 结果
     */
    @Override
    public int updateOrders(Orders orders) {
        // 根据订单ID查询订单信息
        Orders oldOrders = ordersMapper.selectOrdersBynum(orders.getOrderNum());
        if (oldOrders == null) {
            return 0;
        }
        // 0-待支付，1-已完成，2-已取消, 3-已退款， 4-待核销，
        if (oldOrders.getOrderStatus() == 0 && orders.getOrderStatus() == 4) {
            // 支付成功，更新订单状态为已完成
            orders.setOrderStatus(4L);
            int updateOrders = ordersMapper.updateOrders(orders);
                // TODO 判断优惠券是否存在和是否有效
            if (updateOrders > 0) {
                // 生成核销码
                String verifyCode = VerifyCodeGen.genVerifyCode();
                orders.setVerifyCode(verifyCode);
            }
            return updateOrders;
        }
        else if (oldOrders.getOrderStatus() == 0 && orders.getOrderStatus() == 2) {
            // 更新订单状态为已取消
            orders.setOrderStatus(2L);
            int updateOrders = ordersMapper.updateOrders(orders);
            System.out.println("更新订单状态为已取消：" + updateOrders);
            System.out.println("用户优惠券的状态：" + orders.getCvId());
            if (updateOrders > 0) {
                if (orders.getCvId() == null) {
                    return updateOrders;
                }
                // 如果优惠券存在且有效，则更新优惠券的状态
                Coupon coupon = couponMapper.selectCouponByCId(orders.getCvId());
                UserCoupon userCoupon = userCouponMapper.selectByUserIdAndCouponId3(orders.getUserId(), orders.getCvId());
                System.out.println("优惠券信息：" + coupon);
                System.out.println("用户优惠券的状态：" + userCoupon);
                if (coupon != null && coupon.getValidStartTime().before(new Date()) && coupon.getValidEndTime().after(new Date())) {
                    // 更新优惠券的状态
                    System.out.println("更改优惠券状态");
                    System.out.println(userCoupon.getUcId());
                    int i = userCouponMapper.updateUserCouponByUcId(userCoupon.getUcId(), 1L);
                    System.out.println("更改优惠券状态：" + i);
                }else if (userCoupon!= null) {
                    userCouponMapper.updateUserCouponByUcId(userCoupon.getUcId(), 3L);
                }
            }
            return updateOrders;
        }
        else if (oldOrders.getOrderStatus() == 4 && orders.getOrderStatus() == 1) {
            // 核销成功，更新订单状态为已核销
            orders.setOrderStatus(1L);
            int updateOrders = ordersMapper.updateOrders(orders);
            return updateOrders;
        }
        else if (oldOrders.getOrderStatus() == 4 && orders.getOrderStatus() == 3) {
            // 退款成功，更新订单状态为已退款
            orders.setOrderStatus(3L);
            int updateOrders = ordersMapper.updateOrders(orders);
            // TODO 判断优惠券是否存在和是否有效
            if (updateOrders > 0) {
                    // TODO 判断优惠券是否存在和是否有效
                    if (orders.getCvId() == null) {
                        return updateOrders;
                    }
                    // 如果优惠券存在且有效，则更新优惠券的状态
                    Coupon coupon = couponMapper.selectCouponByCId(orders.getCvId());
                UserCoupon userCoupon = userCouponMapper.selectByUserIdAndCouponId3(orders.getUserId(), orders.getCvId());
                    if (coupon != null && coupon.getValidStartTime().before(new Date()) && coupon.getValidEndTime().after(new Date())) {
                        // 更新优惠券的状态
                        System.out.println("更改优惠券状态");
                        int i = userCouponMapper.updateUserCouponByUcId(userCoupon.getUcId(), 1L);
                        System.out.println("更改优惠券状态：" + i);
                    }else if (userCoupon!= null) {
                        userCouponMapper.updateUserCouponByUcId(userCoupon.getUcId(), 3L);
                    }
            }
            return updateOrders;
        }
        return ordersMapper.updateOrders(orders);
    }

    /**
     * 批量删除订单信息
     * 
     * @param oIds 需要删除的订单信息主键
     * @return 结果
     */
    @Override
    public int deleteOrdersByOIds(Long[] oIds) {
        return ordersMapper.deleteOrdersByOIds(oIds);
    }

    /**
     * 删除订单信息信息
     * 
     * @param oId 订单信息主键
     * @return 结果
     */
    @Override
    public int deleteOrdersByOId(Long oId) {
        return ordersMapper.deleteOrdersByOId(oId);
    }


    @Override
    public AjaxResult addWeixiuOrder(Orders orders) {
        // 0-待支付，1-已完成，2-已取消, 3-已退款， 4-待核销，
        Coupon coupon = couponMapper.selectCouponByCId(orders.getCvId());
        System.out.println("优惠券信息：" + coupon);
        // 判断优惠券是否存在和是否有效
        if (coupon == null) {
            return AjaxResult.error("优惠券信息错误");
        }
        if (coupon.getValidStartTime().after(new Date()) || coupon.getValidEndTime().before(new Date())) {
            return AjaxResult.error("优惠券不可使用");
        }
        UserCoupon userCoupon = userCouponMapper.selectByUserIdAndCouponId2(orders.getUserId(), orders.getCvId());
        if (userCoupon == null) {
            return AjaxResult.error("用户暂无可用优惠券");
        }else {
            orders.setUcId(userCoupon.getUcId());
        }
        System.out.println("用户优惠券的状态：" + userCoupon);
        // 生成订单号
        long orderId = redisIdWorker.nextId("order");
        orders.setOrderNum(orderId + "");
        orders.setOrderTime(new Date());
        orders.setOrderTime(new Date());
        orders.setOrderStatus(0L);
        orders.setVerifyCode("");
        orderProducer.sendOrder(orders);
        return AjaxResult.success();
    }
}
